<?php
namespace app\api\controller;

use app\store\model\Setting as SettingModel;
use app\common\extend\Payapi as PayModel;
use app\common\model\User as UserModel;
/**
 * 订单控制器
 * Class Order
 * @package app\api\controller
 */
class Order extends Controller
{
    /**
	 * 购物车列表
	 */
	public function data() {
		$data = [];
		$cart_flag = 1; //是否是购物车购买
		$address_id = $this->request->param('address_id/d' , 0);
		$is_need_paypass = false; //是否需要支付密码
		//购物车ID
		$cart_data = $this->request->param('cart_data' , '');
		//购物车购买
		if( $cart_data ) {
			$list = thumbImgUrl( db("goods_cart")->alias('gc')->join('yoshop_goods g' , 'g.goods_id = gc.goods_id')->join('yoshop_goods_spec gs','g.goods_id = gs.goods_id AND gc.goods_spec_id = gs.goods_spec_id')
					->field("g.goods_id,g.goods_name,g.thumb,g.delivery_id,gs.goods_weight,gc.num,gs.goods_price,gs.spec_sku_id,g.goods_type,g.goods_type_price,g.goods_integral")
					->where(['gc.user_id' => $this->user_info['user_id'] ,'g.is_delete' => 0, 'gc.id' => ['in' , $cart_data]])->select()->each(function($item , $key){
						$item['attr_value'] = '';
						if( $item['spec_sku_id'] ) {
							$value = db("spec_value")->where('spec_value_id IN('.str_replace('_' , ',' , $item['spec_sku_id']).')')->column("spec_value");
							$item['attr_value'] = implode(" + " , $value);
						}
						unset( $item['spec_sku_id'] );
						return $item;
					})->toArray() );
		} else {
			//单独购买
			$goodsid = $this->request->param('goodsid/d' , 0);
			$spec_id = $this->request->param('spec_id/d' , 0);
			$stock = $this->request->param('stock/d' , 1);
			if( $goodsid <= 0 && $spec_id <= 0 ) {
				$this->error('数据异常，请核对');
			}
			if( $goodsid > 0 ) {
				$wheres = ['g.goods_id' => $goodsid,'g.is_delete' => 0];
			} else {
				$wheres = ['gs.goods_spec_id' => $spec_id,'g.is_delete' => 0];
			}
			$list = thumbImgUrl( db('goods')->alias('g')->join("yoshop_goods_spec gs" , 'gs.goods_id = g.goods_id')
					->field("g.goods_name,g.goods_id,g.delivery_id,gs.goods_weight,g.thumb,gs.goods_price,g.goods_type,gs.spec_sku_id,g.goods_type_price,g.goods_integral")
					->where( $wheres )->select()->each(function($item,$key){
						$item['num'] = 0;
						$item['attr_value'] = '';
						if( $item['spec_sku_id'] ) {
							$value = db("spec_value")->where('spec_value_id IN('.str_replace('_' , ',' , $item['spec_sku_id']).')')->column("spec_value");
							$item['attr_value'] = implode(" + " , $value);
						}
						unset( $item['spec_sku_id'] );
						return $item;
					})->toArray() );
			$cart_flag = 2;
		}
		if( !$list ) {
			$this->error('商品数据不存在，请重试');
		}
		$total_price = 0;//总金额
		$delivery_price = 0;//邮费
		$delivery_ids = [];//邮费ID
		$pay_goods_integral = 0; //需要支付的积分
		foreach( $list as $k => &$v ) {
			if( $cart_flag == 2 ) {
				$v['num'] = $stock;
			}
			//获得需要支付的钱
			if( $v['goods_type'] == 1 || ( $v['goods_type'] == 2 && $v['goods_type_price'] == 1 ) ){
				$total_price += $v['goods_price'] * $v['num'];
			}
			//获得用于计算的商品信息以及运费信息
			if( $v['delivery_id'] > 0 ) {
				$delivery_ids[] = [$v['delivery_id'],$v['goods_id'] , $v['num'] , $v['goods_weight']];
			}
			//获得需要支付的积分
			if( $v['goods_type'] == 2 ) {
				$pay_goods_integral += $v['goods_integral'] * $v['num'];
			}
			//如果只是积分兑换则支付金额为0
			if(  $v['goods_type_price'] == 2 ) {
				$total_price = 0;
			}
		}
		
		//获得默认的收货地址
		$address_where = ['user_id' => $this->user_info['user_id']];
		if( $address_id > 0 ) {
			$address_where['id'] = $address_id;
		}
		$address_list = db("user_address")->where( $address_where )->order('is_default DESC')
						->field('id,name,mobile,province_name,city_name,area_name,address')->select()->each(function($item,$key){
							$item['address'] = $item['province_name'].$item['city_name'].$item['area_name'].$item['address'];
							unset( $item['province_name'] );
							unset( $item['city_name'] );
							unset( $item['area_name'] );
							return $item;
						})->toArray();
		$delivery_price = $this->feeprice( $delivery_ids , $address_list ? $address_list[0]['id'] : 0 );
		$total_price += $delivery_price;
		
		$data = [
			'address' => $address_list ? $address_list[0] : [], //收货地址
			'total_price' => $total_price, //商品总价
			'goods_count' => count($list), //商品数量
			'delivery_price' => $delivery_price, //邮费
			'pay_goods_integral' => $pay_goods_integral, //需要支付的积分
			'goods_list' => thumbImgUrl( $list )
		];
		//获得用户的信息
		$userinfo = db("user")->where(['user_id' => $this->user_info['user_id']])->find();
		//获得账户余额信息
		//$data['total_price'] > 0 ? $data['user_money'] = $userinfo['money'] : '';
		//获得积分余额信息
		$data['user_integral'] = $userinfo['integral'];
		//是否已经设置支付密码
		$data['is_setting_paypass'] = 1;
		if( $this->user_info['pay_pass'] ) {
			$data['is_setting_paypass'] = 2;
		}
		$this->success('success' ,  $data );
	}
	
	/**
	 * 创建订单
	 */
	public function create() {
		$data = [];
		$cart_flag = 1; //是否是购物车购买
		$is_pay_status = false; //是否支付
		$cart_data = $this->request->param('cart_data' , '');
		$address_id = $this->request->param("address_id/d" , 0);
		$note = $this->request->param("note" , '');
		$pass = $this->request->param('pass' , '');
		if( $address_id <= 0 ) $this->error('请选择您的收货地址');
		//购物车购买
		if( $cart_data ) {
			$list = db("goods_cart")->alias('gc')->join('yoshop_goods g' , 'g.goods_id = gc.goods_id')->join('yoshop_goods_spec gs','g.goods_id = gs.goods_id AND gc.goods_spec_id = gs.goods_spec_id')
					->field("g.goods_id,g.goods_name,gs.spec_sku_id,gs.goods_no,gs.stock_num,gs.line_price,gs.goods_spec_id,g.thumb,g.delivery_id,g.spec_type,g.deduct_stock_type,gs.goods_weight,gc.num,gs.goods_price,gs.spec_sku_id,g.goods_type,g.goods_type_price,g.goods_integral")
					->where(['gc.user_id' => $this->user_info['user_id'] ,'g.is_delete' => 0, 'gc.id' => ['in' , $cart_data]])->select()->each(function($item , $key){
						$item['attr_value'] = '';
						if( $item['spec_sku_id'] ) {
							$value = db("spec_value")->where('spec_value_id IN('.str_replace('_' , ',' , $item['spec_sku_id']).')')->column("spec_value");
							$item['attr_value'] = implode(" + " , $value);
						}
						return $item;
					})->toArray();
		} else {
			//单独购买
			$goodsid = $this->request->param('goodsid/d' , 0);
			$spec_id = $this->request->param('spec_id/d' , 0);
			$stock = $this->request->param('stock/d' , 1);
			if( $goodsid <= 0 && $spec_id <= 0 ) {
				$this->error('数据异常，请核对');
			}
			if( $goodsid > 0 ) {
				$wheres = ['g.goods_id' => $goodsid,'g.is_delete' => 0];
			} else {
				$wheres = ['gs.goods_spec_id' => $spec_id,'g.is_delete' => 0];
			}
			$list = db('goods')->alias('g')->join("yoshop_goods_spec gs" , 'gs.goods_id = g.goods_id')
					->field("g.goods_name,gs.spec_sku_id,gs.goods_spec_id,gs.line_price,gs.goods_no,gs.stock_num,g.goods_id,g.delivery_id,g.spec_type,g.deduct_stock_type,gs.goods_weight,g.thumb,gs.goods_price,g.goods_type,g.goods_type_price,g.goods_integral")
					->where( $wheres )->select()->each(function($item,$key){
						$item['num'] = 0;
						$item['attr_value'] = '';
						if( $item['spec_sku_id'] ) {
							$value = db("spec_value")->where('spec_value_id IN('.str_replace('_' , ',' , $item['spec_sku_id']).')')->column("spec_value");
							$item['attr_value'] = implode(" + " , $value);
						}
						return $item;
					})->toArray();
			$cart_flag = 2;
		}
		if( !$list ) {
			$this->error('商品数据不存在，请重试');
		}
		$total_price = 0;//总金额
		$delivery_price = 0;//邮费
		$delivery_ids = [];//邮费ID
		$pay_goods_integral = 0; //需要支付的积分
		foreach( $list as $k => &$v ) {
			if( $cart_flag == 2 ) {
				$v['num'] = $stock;
			}
			//获得需要支付的钱
			if( $v['goods_type'] == 1 || ( $v['goods_type'] == 2 && $v['goods_type_price'] == 1 ) ){
				$total_price += $v['goods_price'] * $v['num'];
			}
			//获得用于计算的商品信息以及运费信息
			if( $v['delivery_id'] > 0 ) {
				$delivery_ids[] = [$v['delivery_id'],$v['goods_id'] , $v['num'] , $v['goods_weight']];
			}
			//获得需要支付的积分
			if( $v['goods_type'] == 2 ) {
				$pay_goods_integral += $v['goods_integral'] * $v['num'];
			}
			//如果只是积分兑换则支付金额为0
			if(  $v['goods_type_price'] == 2 ) {
				$total_price = 0;
			}
			
		}
		//判断是否需要二级密码
		if( $pay_goods_integral > 0 ){
			if( !$pass ) {
				$this->error("请输入您的支付密码");
			}
			//判断支付密码是否正确
			$usermode = new UserModel;
			if( $usermode->passmd5($pass) != $this->user_info['pay_pass'] ) {
				$this->error("支付密码错误");
			}
			//判断积分是否住够
			if( $this->user_info['integral'] < $pay_goods_integral ) {
				$this->error("非常抱歉，积分不足");
			}
			//扣除积分
			db("user")->where(['user_id' => $this->user_info['user_id']])->update(['integral' => $this->user_info['integral'] - $pay_goods_integral]);
			//写入日志
			db("user_integral_log")->insert([
				'user_id' => $this->user_info['user_id'],
				'num' => $pay_goods_integral,
				'type' => 2,
				'content' => '兑换产品【'.$list[0]['goods_name'].'】扣除积分【'.$pay_goods_integral.'】',
				'create_time' => time()
			]);
		}
		$delivery_price = $this->feeprice( $delivery_ids , $address_id );
		$total_price += $delivery_price;
		
		//获得收货地址
		$address = db("user_address")->where(['user_id' => $this->user_info['user_id'],'id' => $address_id])->find();
		if( !$address ) {
			$this->error('收货地址错误');
		}
		//订单入库
		$add_data = [
			'order_no' => date('YmdHis').rand(100,999),
			'total_price' => $total_price,
			'pay_price' => $total_price,
			'express_price' => $delivery_price,
			'pay_integral' => $pay_goods_integral,
			'user_id' => $this->user_info['user_id'],
			'type' => $pay_goods_integral > 0 ? 2 : 1,
			'create_time' => time(),
			'update_time' => time(),
			'note' => $note
		];
		//判断需要支付的金额 如果为0则直接支付成功
		if( $total_price <= 0 ) {
			$is_pay_status = true;
			$add_data['pay_status'] = 20;
			$add_data['pay_time'] = time();
			$add_data['pay_type'] = 3;
			$add_data['transaction_id'] = date("YmdHis") . rand(100000,999999);
		}
		//写入订单表
		$result = db("order")->insert($add_data);
		if( $result ) {
			$order_id = db("order")->getLastInsID();
			//收货地址入库
			db("order_address")->insert([
				'name' => $address['name'],
				'phone' => $address['mobile'],
				'province_id' => $address['province'],
				'city_id' => $address['city'],
				'region_id' => $address['area'],
				'detail' => $address['address'],
				'order_id' => $order_id,
				'user_id' => $this->user_info['user_id'],
				'create_time' => time()
			]);
			
			//商品信息入库
			foreach( $list as $k => $v ) {
				db("order_goods")->insert([
					'goods_id' => $v['goods_id'],
					'goods_name' => $v['goods_name'],
					'thumb' => $v['thumb'],
					'deduct_stock_type' => $v['deduct_stock_type'],
					'spec_type' => $v['spec_type'],
					'spec_sku_id' => $v['spec_sku_id'],
					'goods_spec_id' => $v['goods_spec_id'],
					'goods_attr' => $v['attr_value'],
					'content' => $v['goods_name'],
					'goods_no' => $v['goods_no'],
					'goods_price' => $v['goods_price'],
					'line_price' => $v['line_price'],
					'goods_weight' => $v['goods_weight'],
					'goods_integral' => $v['goods_integral'],
					'total_num' => $v['num'],
					'total_price' => $v['num'] * $v['goods_price'],
					'order_id' => $order_id,
					'user_id' => $this->user_info['user_id'],
					'create_time' => time()
				]);
				//修改商品库存、增加销量
				$stock_num = $v['stock_num'] - $v['num'];
				db("goods")->where(['goods_id' => $v['goods_id']])->setInc("sales_actual");
				db('goods_spec')->where(['goods_spec_id' => $v['goods_spec_id']])->update(['stock_num' => $stock_num > 0 ? $stock_num : 0]);
			}
			//判断是否是购物车购买
			if( $cart_data ) {
				db("goods_cart")->where(['id' => ['in' , $cart_data]])->delete();
			}
			$this->success('订单创建成功' , ['type' => $is_pay_status == true ? 2 : 1 , 'order_id' => $order_id]);
		} else {
			$this->error('订单创建失败,请重新创建');
		}
	}
	
	/**
	 * 订单支付
	 */
	public function pay() {
		$order_id = $this->request->param("order_id/d" , 0);
		if( $order_id <= 0 ) $this->error('订单数据错误');
		$order_info = db("order")->field("order_no,total_price,pay_price,pay_status,pay_integral")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $order_id])->find();
		if( !$order_info ) $this->error('订单信息不存在');
		if( $order_info['pay_status'] == 20 ){
			$this->error('订单已支付，请勿重复支付');
		}
		$pay = new PayModel;
		$order_info['pay']['wx'] = $pay->payment( $order_info , 2 );
		$order_info['pay']['ali'] = $pay->payment( $order_info , 1 );
		$order_info['pay']['locals'] = $this->user_info['money'];
		return $this->renderSuccess(compact('order_info'));
	}
	
	/**
	 * 获得运费
	 */
	private function feeprice( $data , $address_id) {
		if( !$data || !$address_id ) return 0;
		$config = SettingModel::getItem('trade');
		$new_data = [];
		foreach( $data as $k => $v ) {
			$new_data[$v[0]] = $v;
		}
		$delivery_ids = array_column($data, 0);
		//获得收货地址信息
		$address = db("user_address")->where(['user_id' => $this->user_info['user_id'],'id' => $address_id])->find();
		
		//获得模板列表
		$delivery_data = db("delivery")->alias("d")->join("yoshop_delivery_rule r" , 'r.delivery_id = d.delivery_id')->where("d.delivery_id IN(".implode("," , $delivery_ids).")")
						 ->field("d.method,r.*")->select();
		if( !$delivery_data ) return 0;
		$fee_data = [];
		//计算每个商品的运费
		foreach( $delivery_data as $k => $v ) {
			//判断运费是否已经计算 以计算则直接跳过
			//if( isset( $fee_data[$v['delivery_id']] ) && $fee_data[$v['delivery_id']] > 0 ) continue;
			if( $v['region'] && strpos(','.$v['region'].',' , ','.$address['city'].',') !== false ) {
				if( $v['method'] == 10 ) { //按件
					$field = 2;
				} else { //按重量
					$field = 3;
				}
				if( $v['first'] >= $new_data[$v['delivery_id']][$field] ) {
					$fee_data[] = $v['first_fee']; //$v['delivery_id']
				} else {
					$duo_num = $new_data[$v['delivery_id']][$field] - $v['first'];
					$fee_data[] = $duo_num <= 0 || $v['additional'] <= 0 || $v['additional_fee'] <= 0 ? 0 : ( $v['first_fee'] + ( ceil( $duo_num / $v['additional'] ) * $v['additional_fee'] ) ); //$v['delivery_id']
				}
			} else {
				$fee_data[] = 0; //$v['delivery_id']
			}
		}
		switch( $config['freight_rule'] ) {
			case 10 :
				return array_sum( $fee_data );
			break;
			case 20 :
				sort( $fee_data );
				return $fee_data[0];
			break;
			case 30 :
				rsort( $fee_data );
				return $fee_data[0];
			break;
		}
	}
	
	/**
	 * 支付成功页面
	 */
	public function paysuccess() {
		$order_id = $this->request->param("order_id/d" , 0);
		if( $order_id <= 0 ) $this->error('订单数据错误');
		$order_info = db("order")->field("order_no,total_price,pay_price,pay_status,pay_integral,pay_time,transaction_id,pay_type")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $order_id])->find();
		if( !$order_info ) $this->error('订单信息不存在');
		if( $order_info['pay_status'] != 20 ) $this->error('订单未支付，请支付订单');
		return $this->renderSuccess(compact('order_info'));
	}
	
	/**
	 * 订单支付
	 */
	public function localpay() {
		$order_id = $this->request->param("order_id/d" , 0);
		if( $order_id <= 0 ) $this->error('订单数据错误');
		$order_info = db("order")->where(['user_id' => $this->user_info['user_id'] , 'order_id' => $order_id])->find();
		if( !$order_info ) $this->error('订单信息不存在');
		if( $order_info['pay_status'] == 20 ) {
			$this->error('订单已支付，请勿重复支付');
		}
		if( $order_info['pay_price'] > 0 && $this->user_info['money'] >= $order_info['pay_price'] ) {
			//扣除本地金额
			db("user")->where(['user_id' => $this->user_info['user_id']])->update(['money' => $this->user_info['money'] - $order_info['pay_price']]);
			//写入日志
			db("user_money_log")->insert([
				'user_id' => $this->user_info['user_id'],
				'num' => $order_info['pay_price'],
				'type' => 2,
				'content' => '支付【'.$order_info['order_no'].'】订单,扣除账户余额【'.$order_info['pay_price'].'】',
				'create_time' => time()
			]);
			//修改订单状态
			db("order")->where(['order_id' => $order_id])->update(['pay_type' => 3 , 'pay_status' => 20 , 'pay_time' => time() , 'transaction_id' => date("YmdHis") . rand(100000,999999)]);
			$this->success('支付成功', ['order_id' => $order_id]);
		} else {
			$this->error('支付余额不足');
		}
	}
}